package com.frxuexi.cart.view

import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.frxuexi.cart.viewmodel.CartViewModel
import com.frxuexi.cart.databinding.ActivityAddreddEditBinding
import com.frxuexi.lib_base.entity.Address
import com.frxuexi.lib_base.entity.EditAddressReq
import com.frxuexi.lib_base.mvvm.BaseActivity
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import dagger.hilt.android.AndroidEntryPoint

@Route(path = "/cart/AddreddEditActivity")
@AndroidEntryPoint
class AddreddEditActivity : BaseActivity<ActivityAddreddEditBinding, CartViewModel>() {
    lateinit var address: Address

    @JvmField
    @Autowired
    var id: Int? = -1
    override fun initData() {
        vm.editAddressData.observe(this) {
            finish()
        }

        vm.addressByIdData.observe(this) {
            //把要修改的地址信息显示
            binding.editName.setText(it.realName)
            binding.editPhone.setText(it.phone)
            binding.editDetail.setText(it.detail)
            binding.editAddress.setText("${it.province},${it.city},${it.district}")
            binding.editMo.isChecked = it.isDefault
            address = Address(it.city, 0, it.district, it.province)
        }

    }

    override fun initView() {
        ARouter.getInstance().inject(this)

        //编辑
        if (id != -1) {
//            查询地址详情
            vm.getAddressById(id!!)
        }


        binding.editAddress.setOnClickListener {
//选择地址
            val picker = AddressPicker(this)
            picker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY)
            picker.setOnAddressPickedListener { province, city, county ->
                binding.editAddress.setText("${province.name},${city.name},${county.name}")
                address = Address(city.name, 0, county.name, province.name)
            }
            picker.show()
        }

        binding.editSave.setOnClickListener {
            val checked = binding.editMo.isChecked
            val phone = binding.editPhone.text.toString()
            val name = binding.editName.text.toString()
            val req = EditAddressReq(
                address,
                checked,
                binding.editDetail.text.toString(),
                null,
                checked,
                phone,
                name
            )
            if (id != -1) {
//                修改需要id
                req.id = id
            }
            vm.editAddress(req)
        }
    }

}